import React, { useState, useEffect, useMemo } from "react";
import { LeftOutline, LikeOutline, MessageOutline, MoreOutline, StarOutline } from "antd-mobile-icons";
import './less/Detail.less'
import { Badge, Toast } from "antd-mobile";
import SkeletonAgain from '../components/SkeletonAgain'
import api from '../api';
import { flushSync } from "react-dom";
import _ from '../assets/utils'
import { connect } from "react-redux";
import action from "../store/action";

const Detail = function (props) {
    let { navigate, params } = props;
    //定义状态
    let [info, setInfo] = useState(null);
    let [extra, setExtra] = useState(null);

    let link;
    const handleStyle = (res) => {
        let { css } = res;
        if (!Array.isArray(css)) return;
        css = css[0];
        if (!css) return;
        link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = css;
        document.head.appendChild(link);
    };
    const handleImage = (res) => {
        let imgPlaceHolder = document.querySelector(".img-place-holder");
        if (!imgPlaceHolder) return;
        //设置底边标题
        let detailTitleBox = document.createElement('div');
        detailTitleBox.className = "detail-title-box";
        detailTitleBox.innerHTML = `<p>${res.title}</p>`
        //设置底边模糊
        let bgColor = res.image_hue.slice(2);
        bgColor = "#" + bgColor;
        detailTitleBox.style.background = `linear-gradient(to bottom,${_.colorRgb(bgColor, "0")}, ${_.colorRgb(bgColor, "1")})`
        let tempImage = new Image;
        tempImage.src = res.image;
        tempImage.onload = () => {
            imgPlaceHolder.appendChild(tempImage);
            imgPlaceHolder.appendChild(detailTitleBox);
        }
        tempImage.onerror = () => {
            imgPlaceHolder.parentNode.parentNode.removeChild(imgPlaceHolder.parentNode);
        }
    };
    //第一次渲染完毕，请求数据
    useEffect(() => {
        (async () => {
            try {
                let res = await api.queryNewsInfo(params.id);
                flushSync(() => {
                    setInfo(res);
                    //处理样式和图片
                    handleStyle(res);
                })
                handleImage(res);
            } catch (err) {
                console.log(err);
            }
        })()

        //销毁组件，移除创建的样式
        return () => {
            if (link) document.head.removeChild(link);
        }
    }, [])
    useEffect(() => {
        (async () => {
            try {
                let res = await api.queryStoryExtra(params.id);
                setExtra(res)
            } catch (err) {
                console.log(err);
            }
        })()
    }, [])

    //登录收藏
    let { base: { info: userInfo }, queryUserInfoAsync, location,
        store: { list: storeList }, queryStoreListAsync, removeStoreListById
    } = props;
    useEffect(() => {
        (async () => {
            //第一次渲染完，如果userInfo不存在，则派发任务同步登录者信息
            if (!userInfo) {
                let { info } = await queryUserInfoAsync();
                userInfo = info;
            }
            //如果已经登录没有收藏信息，则派发任务同步收藏信息
            if (userInfo && !storeList) {
                queryStoreListAsync();
            }
        })()
    }, [])
    //依赖于收藏列表和路径参数来计算是否在收藏中
    const isStore = useMemo(() => {
        if (!storeList) return false;
        return storeList.some(item => {
            return +item.news.id === +params.id;
        });
    }, [storeList, params]);
    //点击收藏按钮
    const handleStore = async () => {
        if (!userInfo) {
            Toast.show({
                icon: 'fail',
                content: '请先登录'
            })
            navigate(`/login?to=${location.pathname}`, { replace: true })
            return
        }
        //已经登录 收藏或移除收藏
        if(isStore) {
            //移除收藏
            let item = storeList.find(item => {
                return +item.news.id === +params.id
            })
            if(!item) return;
            let {code} = await api.storeRemove(item.id);
            if(+code !== 0) {
                Toast.show({
                    icon: 'fail',
                    content: '操作失败'
                })
                return
            }
            Toast.show({
                icon: 'success',
                content: '操作成功'
            })
            removeStoreListById(item.id)//；移除redux中的数据
            return
        }
        //收藏
        try {
            let {code} = await api.store(params.id);
            if(+code !== 0) {
                Toast.show({
                    icon: 'fail',
                    content: '收藏失败'
                })
                return
            }
            Toast.show({
                icon: 'success',
                content: '收藏成功'
            })
            queryStoreListAsync()//同步最新的收藏列表到redux容器中
            return
        } catch (error) {
            
        }
    }
    return <div className="detail-box">
        {info ? <div className="content"
            dangerouslySetInnerHTML={{ __html: info.body }}>
        </div>
            : <SkeletonAgain />}
        <div className="tab-bar">
            <div className="back"
                onClick={() => {
                    navigate(-1);
                }}
            >
                <LeftOutline />
            </div>
            <div className="icons">
                <Badge content={extra ? extra.comments : null}><MessageOutline /></Badge>
                <Badge content={extra ? extra.popularity : null}><LikeOutline /></Badge>
                <span className={isStore ? 'stored' : ''}
                    onClick={handleStore}
                ><StarOutline /></span>
                <span><MoreOutline /></span>
            </div>
        </div>
    </div>
}
export default connect(
    state => {
        return {
            base: state.base,
            store: state.store
        };
    },
    { ...action.base, ...action.store }
)(Detail);